#! /usr/local/bin/python

# Web 2.0 API

import cgitb; cgitb.enable()
import cgi
import sys
import urllib
import urllib2
from xml.dom import minidom

def getText(nodelist):
    rc = []
    for node in nodelist:
        if node.nodeType == node.TEXT_NODE:
            rc.append(node.data)
    return ''.join(rc)

file = urllib2.urlopen('http://personal.cs.cityu.edu.hk/~51158405/blog/api/user.xml')
data = file.read()
file.close()

xmldoc = minidom.parseString(data)

# get form variables (if desired)
form = cgi.FieldStorage()
if 'id' in form:
    uid = form['id'].value
else:
    uid = ''
    #sys.exit()

name = ''

users = xmldoc.getElementsByTagName("user")
for user in users:
    _id = getText(user.getElementsByTagName("id")[0].childNodes)
    if uid == _id:
        name = getText(user.getElementsByTagName("name")[0].childNodes)
        break

# print out the content header
print 'Content-type: text/html\n\n'
print name
